package top.hmtools.wxmp.core.access_handle;

import java.io.File;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import org.apache.commons.io.FileUtils;

import top.hmtools.wxmp.core.model.AccessTokenBean;

public class DefaultAccessTokenHandle extends BaseAccessTokenHandle {
	
	private volatile AccessTokenBean accessTokenBean;
	
	/**
	 * 序列化时，存放在磁盘上的路径
	 */
	private String atBeanSerializablePath = System.getProperty("user.dir")+File.separator+"atBean.bean";

	@Override
	public AccessTokenBean getAccessTokenBeanFromStorage() {
		if(this.accessTokenBean != null){
			return this.accessTokenBean;
		}else{
			//先尝试从磁盘中获取序列化的atbean
			ObjectInputStream ois = null;
			try{
				File file = new File(atBeanSerializablePath);
				if(file.exists()){
					this.logger.debug("access token序列化文件存放路径：{}",file.getAbsoluteFile());
					ois = new ObjectInputStream(FileUtils.openInputStream(file.getAbsoluteFile()));
					this.accessTokenBean = (AccessTokenBean) ois.readObject();
					this.logger.info("从本地磁盘获取序列化的accessToken成功：{}",this.accessTokenBean);
				}
			}catch(IOException | ClassNotFoundException e){
				this.logger.error("从本地磁盘获取序列化的accessToken异常：",e);
			}finally{
				try {
					if(ois!=null){
						ois.close();
					}
				} catch (IOException e) {
					this.logger.error("",e);
				}
			}
			return  this.accessTokenBean;
		}
	}

	@Override
	public void saveAccessTokenBeanToStorage(AccessTokenBean accessTokenBean) {
		if(accessTokenBean == null){
			throw new IllegalArgumentException("入参为空");
		}
		synchronized(accessTokenBean){
			this.doSerializable(accessTokenBean);
			this.accessTokenBean = accessTokenBean;
		}
	}
	
	/**
	 * 执行序列化
	 * @param atBean
	 */
	private void doSerializable(AccessTokenBean atBean){
		try {
			ObjectOutputStream oos = new ObjectOutputStream(FileUtils.openOutputStream(new File(this.atBeanSerializablePath)));
			oos.writeObject(atBean);
			this.logger.info("序列化accessToken：{}到磁盘成功",atBean);
		} catch (IOException e) {
			this.logger.error("序列化access Token： "+atBean+" 信息失败："+e.getMessage(),e);
		}
	}

}
